


const VERSION = "v1.1.1";
const CACHE_FILES = [
    // /\/[\w\W]+(\.\w+)$/,// /aa.vv
    // "/"
];
self.addEventListener('install', function (event) {
    //初始化缓存
    postMessage({
        type: 'install',
        // event
    });
    event.waitUntil(caches.open(VERSION).then(function (cache) {
        return cache.addAll(CACHE_FILES);
    }));
    //直接进行激活
    // event.waitUntil(self.skipWaiting());
});

//当安装成功后，serviceworker就会激活，这时就会处理 activate 事件回调
//监听activate事件，激活后通过cache的key来判断是否更新cache中的静态资源
//每次加载页面都执行
self.addEventListener('activate', function (event) {
    postMessage({
        type: 'activate',
        // event
    });
    event.waitUntil(Promise.all([cleanCaches(), self.clients.claim()/*当前sw获取所有页面控制权*/]));
});

//来之页面的消息
self.addEventListener('message', function (event) {
    const data = event.data;
    postMessage({
        type: 'message',
        data,
    });
    if (data === 'skipWaiting') {
        self.skipWaiting();//手动直接进行激活操作
    } else if (data === 'updateCache') {
        updateCache(event);
    }
})

self.addEventListener('fetch', function (event) {
    // 判断当前请求是否需要缓存
    postMessage({
        type: 'fetch',
        data: event.request.url,
    });
    const needCache = CACHE_FILES.some(function (url) {
        return event.request.url.match(url);
    });
    if (needCache) {
        event.respondWith(
            caches.match(event.request).then(function (cache) {
                if (cache) return cache;
                return fetchCache(event);
            }).catch(function (err) {
                console.log('fetch', err);
                return fetchCache(event);
            })
        );
    }
})

// 来自其他客户端
self.addEventListener('notificationclick', async function (event) {
    postMessage({
        type: 'notificationclick',
        // event
    });
    const action = event.action;
    if (action === 'update') {
        await updateCache(event)
    }
    event.notification.close();//
    return event.waitUntil(self.clients.matchAll().then(function (clients) {
        // 获取所有clients
        if (!clients || clients.length == 0) {
            // self.clients.openWindow && self.clients.openWindow('http://127.0.0.1');
            return;
        }
        let hasFoucs = false;
        clients.forEach(function (client) {
            if (client.focused) hasFoucs = true;
            //使用postMessage进行通信
            //向所有客户端发出消息
            client.postMessage(action);
        });
        if (hasFoucs) {
            clients[0].focus && clients[0].focus();
        }
        //使用当前激活的sw控制权
        self.clients.claim();//claim() 方法允许一个激活的 service worker 将自己设置为其 scope 内所有clients 的controller
    }));
})

async function updateCache(event) {
    await event.waitUntil(cleanCaches(true));
    postMessage({
        type: 'updatedCache',
        // event
    });
}
// 点击关闭通知后触发
self.addEventListener('notificationclose', function (event) {
    postMessage({
        type: 'notificationclose',
        // event
    });
    console.log("self notificationclose")
});


//为 SW 提供一个可以实现注册和监听同步处理的方法
self.addEventListener('sync', function (event) {
    const tag = event.tag;
    postMessage({
        type: 'sync',
        data: tag
    });
    if (tag === 'sync1') {
        const request = new Request(`sync`, { method: "POST" });
        e.waitUntil(//后台一直循环运行，直到成功，
            fetch(request).then(function (response) {
                response.json().then(console.log.bind(console));
                return response;
            })
        );
    } else {

    }
})

/* ======================================= */
/* push处理相关部分，已添加对notification的调用 */
/* ======================================= */
self.addEventListener('push', function (event) {
    let data = event.data;
    postMessage({
        type: 'push',
        data:data.text()
    });
    data = event.data.json()
    // body: data.body || '默认消息内容',
    //     icon: data.icon || 'icon.png', // 替换为你的图标路径
    //     badge: data.badge || 'badge.png', // 替换为你的徽章路径
    //     data: {
    //     url: data.url || '/' // 通知点击时跳转的URL
    // }
    self.registration.showNotification(data.title, {
        tag: 'pwa',
        data: {
                url: data.url || '/' // 通知点击时跳转的URL
            },
        body: data.body||"Explosive news",
        icon: data.icon||'kk71/jiliko.jpg',
        badge: data.badge||'kk71/jiliko.jpg', // no effect
        // actions: [{
        //     action: 'action1',
        //     title: 'title1'
        // }, {
        //     action: 'action2',
        //     title: 'title2'
        // }],
        renotify: true
    });
})

self.addEventListener('notificationclick', function(event) {
    event.notification.close();

    // event.waitUntil(
    //     clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function(clientList) {
    //         for (let i = 0; i < clientList.length; i++) {
    //             let client = clientList[i];
    //             if (client.url === event.notification.data.url && 'focus' in client) {
    //                 return client.focus();
    //             }
    //         }
    //         if (clients.openWindow) {
    //             return clients.openWindow(event.notification.data.url);
    //         }
    //     })
    // );

    event.waitUntil(clients.matchAll({
        type: "window",
        includeUncontrolled: true
    }).then(function (clientList) {
        if (event.notification.data.url) {
            let client = null;

            for (let i = 0; i < clientList.length; i++) {
                let item = clientList[i];

                if (item.url) {
                    client = item;
                    break;
                }
            }

            if (client && 'navigate' in client) {
                client.focus();
                event.notification.close();
                return client.navigate(event.notification.data.url);
            }
            else {
                event.notification.close();
                // if client doesn't have navigate function, try to open a new browser window
                return clients.openWindow(event.notification.data.url);
            }
        }
    }));

});

/**
 * 缓存所需数据
 * @param {*} event
 */
function fetchCache(event) {
    const requestToCache = event.request.clone();
    return fetch(requestToCache).then(function (response) {
        if (!response || response.status !== 200) {
            return response;
        }
        const responseToCache = response.clone();
        caches.open(VERSION).then(function (cache) {
            cache.put(requestToCache, responseToCache);
        })
        return response;
    });
}

/**
 * 清除所有缓存
 * @param {*}
 */
function cleanCaches(isAll) {
    // 清理旧版本
    return caches.keys().then(function (cacheList) {
        return Promise.all(
            cacheList.map(function (cacheName) {
                console.log("cacheName", cacheName)
                if (isAll) return caches.delete(cacheName);//删除所有版本
                if (cacheName !== VERSION) return caches.delete(cacheName);//删除特定版本
            })
        );
    })
}


// 当网络状态发生变化时，会触发 online 或 offline 事件
self.addEventListener('offline ', function (event) {
    postMessage({
        type: 'offline',
        // event
    });
    const notification = new Notification("Hi，网络不给力哟", {
        body: '您的网络貌似离线了，不过在志文工作室里访问过的页面还可以继续打开~',
    });
    notification.onclick = function () {
        notification.close();
    };
});

// 当网络状态发生变化时，会触发 online 或 offline 事件
self.addEventListener('online ', function (event) {
    postMessage({
        type: 'online',
        // event
    });
    const notification = new Notification("Hi，网络已连接");
    notification.onclick = function () {
        notification.close();
    };
});


self.addEventListener('error', function (event) {
    postMessage({
        type: 'error',
        // event
    });
});


async function postMessage(data) {
    const clients = await self.clients.matchAll()
    clients.forEach(function (client) {
        //使用postMessage进行通信
        //向所有客户端发出消息
        client.postMessage(data);
    });
}
